<template>
  <div class="app-container">
    <div class="operation-container">
      <div class="filter-container">
        <el-form :inline="true" label-width="72px">
          <el-form-item label="角色名称">
            <el-input v-model="listQuery.name" placeholder="请输入角色名称" class="filter-item" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="listQuery.status" placeholder="全部" class="filter-item">
              <el-option value="">全部</el-option>
              <el-option
                v-for="item in dict['sys_status']"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item" round icon="el-icon-search" @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-button class="filter-item" type="primary" round icon="el-icon-edit" @click="handleCreate">
        添加角色
      </el-button>
    </div>
    <div class="operation-container">
      <el-table
        ref="roleTable"
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        row-key="id"
        stripe
        highlight-current-row
      >
        <el-table-column
          label="序号"
          type="index"
          :index="indexMethod"
        />
        <el-table-column label="角色名称" prop="title">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="mark"
          label="角色标识"
        />
        <el-table-column
          prop="sort"
          label="排序"
          sortable
          width="100"
        />
        <el-table-column label="状态" prop="status" width="100">
          <template slot-scope="{row}">
            <template v-for="(item,index) in dict['sys_status']">
              <el-tag v-if="item.value === row.status" :key="index" :type="item.listClass">{{ item.label }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createByName" />
        <el-table-column label="创建时间" prop="createTime">
          <template slot-scope="{row}">
            <i class="el-icon-time margin-right-5" />
            <span>{{ row.createTime | dateFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="text" @click="handleUpdate(row)">
              <i class="el-icon-edit" />修改
            </el-button>

            <el-button type="text" @click="handleDelete(row)">
              <i class="el-icon-delete" />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNumber" :limit.sync="listQuery.pageSize" @pagination="getList" />
    </div>

    <!-- 新增编辑角色 -->
    <el-dialog :title="textMap[dialogStatus]" width="500px" append-to-body :visible.sync="dialog">
      <el-form
        ref="dataForm"
        label-width="100px"
        :model="role"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="role.name" />
        </el-form-item>
        <el-form-item label="角色标识" prop="mark">
          <el-input v-model="role.mark" />
        </el-form-item>
        <el-form-item
          label="排序"
          prop="sort"
          style="width: 50%;"
        >
          <el-input-number v-model="role.sort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <template v-for="(item,index) in dict['sys_status']">
            <el-radio :key="index" v-model="role.status" :label="item.value">{{ item.label }}</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            ref="tree"
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            node-key="id"
            empty-text="加载中，请稍后"
            :default-checked-keys="role.ids"
            :props="defaultProps"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="role.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { mapGetters } from 'vuex'
import { fetchList, create, update, deletes } from '@/api/role'
import { roleMenu } from '@/api/menu'
import { tree } from '@/api/menu'
import Pagination from '@/components/Pagination'

export default {
  name: 'RoleTable',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      listLoading: true,
      total: 0,
      list: [],
      listQuery: {
        pageNumber: 1,
        pageSize: 10,
        name: '',
        status: ''
      },
      textMap: {
        update: '修改角色',
        create: '添加角色'
      },
      dialog: false,
      dialogStatus: '',
      menuOptions: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空' }
        ],
        mark: [
          { required: true, message: '角色标识不能为空' }
        ],
        sort: [
          { required: true, message: '排序不能为空' },
          { type: 'number', message: '排序必须为数字值' }
        ]
      },
      role: {
        id: undefined,
        name: undefined,
        mark: undefined,
        sort: undefined,
        status: 'Y',
        ids: [],
        remark: undefined
      }
    }
  },
  computed: {
    ...mapGetters([
      'dict'
    ])
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.2 * 1000)
      })
    },
    getMenuTree() {
      tree().then(response => {
        this.menuOptions = response.data
      })
    },
    indexMethod(index) {
      return index + 1
    },
    // 创建事件
    handleCreate() {
      this.resetFields()
      this.getMenuTree()
      this.dialogStatus = 'create'
    },
    // 修改事件
    handleUpdate(row) {
      this.resetFields()
      this.role = Object.assign({}, row)
      roleMenu(row.id).then(response => {
        this.role.ids = response.data.ids
        this.menuOptions = response.data.list
      })
      this.dialogStatus = 'update'
    },
    submitForm() {
      this.role.ids = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.role.id) {
            update(this.role.id, this.role).then(() => {
              this.dialog = false
              this.getList()
              this.$notify({
                title: '修改完成',
                message: '修改角色:（' + this.role.name + '）信息成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            create(this.role).then(() => {
              this.dialog = false
              this.getList()
              this.$notify({
                title: '新增完成',
                message: '新增角色:（' + this.role.name + '）信息成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      })
    },
    // 删除事件
    handleDelete(row) {
      this.listLoading = true
      deletes(row.id).then(response => {
        this.getList()
        this.$notify({
          title: '删除完成',
          message: '删除角色:（' + row.name + '） 成功！',
          type: 'success',
          duration: 2000
        })
      })
    },
    // 查询事件
    handleFilter() {
      this.listQuery.pageNumber = 1
      this.getList()
    },
    // 重置查询事件
    handleReset() {
      this.listQuery = {
        pageNumber: 1,
        pageSize: 10,
        name: '',
        status: ''
      }
    },
    resetFields() {
      this.role = {
        id: undefined,
        name: undefined,
        mark: undefined,
        sort: undefined,
        status: 'Y',
        ids: [],
        remark: undefined
      }
      if (this.$refs['dataForm'] !== undefined) {
        this.$refs['dataForm'].resetFields()
      }
      this.dialog = true
    }
  }
}

</script>
